//
//  KStatusTableViewCell.m
//  Keping
//
//  Created by 柯平 on 2017/10/22.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KStatusTableViewCell.h"
#import "KStatusData.h"
#import "UIView+KP.h"




@implementation KStatusView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = 1.0f;
    }
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor clearColor];
    self.exclusiveTouch = YES;
    
//    @weakify(self);
    
    //容器
    _contentView = [UIView new];
    _contentView.width = kScreenWidth;
    _contentView.height = 1.0;
    _contentView.backgroundColor = kWhiteColor;
    [self addSubview:_contentView];
    
    //头像
    _avatarView = [UIImageView new];
    _avatarView.clipsToBounds = YES;
    _avatarView.layer.cornerRadius = 5.;
    _avatarView.contentMode = UIViewContentModeScaleAspectFill;
    _avatarView.size = CGSizeMake(KStatusCellAvatarWH, KStatusCellAvatarWH);
    UILongPressGestureRecognizer *lng = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionForLongUser)];
    [_avatarView addGestureRecognizer:lng];
    _avatarView.userInteractionEnabled = YES;
    _avatarView.origin = CGPointMake(KStatusCellPadding, KStatusCellPadding+3);
    [_contentView addSubview:_avatarView];
    [_avatarView setTapActionWithBlock:^{
        //点击图像
    }];
    
    //名字
    _nameLabel = [YYLabel new];
    _nameLabel.size = CGSizeMake(KStatusCellContentWidth-KStatusCellAvatarWH-KStatusCellPadding*3, 24);
//    _nameLabel.font = [UIFont boldSystemFontOfSize:15];
    _nameLabel.left = _avatarView.right+KStatusCellPadding;
    _nameLabel.top = KStatusCellPadding;
    _nameLabel.displaysAsynchronously = YES;
    _nameLabel.ignoreCommonProperties = YES;
    _nameLabel.fadeOnAsynchronouslyDisplay = NO;
    _nameLabel.fadeOnHighlight = NO;
    _nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _nameLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        //点击名字
    };
    [_contentView addSubview:_nameLabel];
    
    //时间
    _timeLabel = [YYLabel new];
    _timeLabel.size = _nameLabel.size;
    _timeLabel.textColor = [UIColor grayColor];
    _timeLabel.font = _nameLabel.font;
    _timeLabel.left = _nameLabel.left;
    _timeLabel.top = _nameLabel.bottom;
    _timeLabel.displaysAsynchronously = YES;
    _timeLabel.ignoreCommonProperties = YES;
    _timeLabel.fadeOnAsynchronouslyDisplay = NO;
    _timeLabel.fadeOnHighlight = NO;
    _timeLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_contentView addSubview:_timeLabel];
    
    //文本
    _contentLabel = [YYLabel new];
    _contentLabel.font = [UIFont boldSystemFontOfSize:15];
    _contentLabel.left = _avatarView.left;
    _contentLabel.top = _avatarView.bottom + 5;
    _contentLabel.width = KStatusCellContentWidth;
    _contentLabel.displaysAsynchronously = YES;
    _contentLabel.ignoreCommonProperties = YES;
    _contentLabel.fadeOnAsynchronouslyDisplay = NO;
    _contentLabel.fadeOnHighlight = NO;
    _contentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_contentView addSubview:_contentLabel];
    
    //图片
    NSMutableArray *picViews = [NSMutableArray new];
    for (int i = 0; i < 9; i++) {
        UIImageView *imageView = [UIImageView new];
        imageView.size = CGSizeMake(100, 100);
        imageView.hidden = YES;
        imageView.tag = 100 + i;
        imageView.clipsToBounds = YES;
        imageView.backgroundColor = UIColorHex(f0f0ff0);
        imageView.exclusiveTouch = YES;
        WEAKSELF
        [imageView setTapActionWithBlock:^{
            //点击图片
            if (weakSelf.cell.delegate && [weakSelf.cell.delegate respondsToSelector:@selector(didClickImages:Index:)]) {
                [weakSelf.cell.delegate didClickImages:weakSelf.layout Index:imageView.tag - 100];
            }
        }];
        [picViews addObject:imageView];
        [_contentView addSubview:imageView];
    }
    _picViews = picViews;
    
    //喜欢
    _likesLabel = [YYLabel new];
    _likesLabel.font = [UIFont boldSystemFontOfSize:15];
    _likesLabel.textColor = [UIColor grayColor];;
    _likesLabel.backgroundColor = kWhiteColor;
    _likesLabel.left = _avatarView.left;
    _likesLabel.displaysAsynchronously = YES;
    _likesLabel.ignoreCommonProperties = YES;
    _likesLabel.fadeOnAsynchronouslyDisplay = NO;
    _likesLabel.fadeOnHighlight = NO;
    _likesLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_contentView addSubview:_likesLabel];
    
    //评论人数
    _commentsLabel = [YYLabel new];
    _commentsLabel.font = [UIFont boldSystemFontOfSize:15];
    _commentsLabel.displaysAsynchronously = YES;
    _commentsLabel.backgroundColor = kWhiteColor;
    _commentsLabel.ignoreCommonProperties = YES;
    _commentsLabel.fadeOnAsynchronouslyDisplay = NO;
    _commentsLabel.fadeOnHighlight = NO;
    _commentsLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _commentsLabel.textAlignment = NSTextAlignmentRight;
    _commentsLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionForCommentLabel)];
    [_commentsLabel addGestureRecognizer:gesture];
    [_contentView addSubview:_commentsLabel];
    
    _seperateLine = [UIView new];
    _seperateLine.backgroundColor = RGBCOLOR(190, 190, 190);
    _seperateLine.size = CGSizeMake(kScreenWidth, 1);
    [_contentView addSubview:_seperateLine];
    
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentButton.size = CGSizeMake(85, 13);
    [_commentButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [_commentButton setImage:[UIImage imageNamed:@"comment"] forState:UIControlStateNormal];
    [_commentButton setTitle:@" Comment" forState:UIControlStateNormal];
    [_commentButton setTitleColor:kGrayColor forState:UIControlStateNormal];
    _commentButton.titleLabel.font = SystemSmallFont;
    [_commentButton addTarget:self action:@selector(actionForComment:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_commentButton];

//    _commentLabel = [UILabel new];
//    _commentLabel.text = @"Comment";
//    _commentLabel.textColor = kGrayColor;
//    _commentLabel.font = SystemSmallFont;
//    _commentLabel.textAlignment = NSTextAlignmentCenter;
//    [_commentLabel setFrame:CGRectMake(_commentButton.right, _commentButton.top, 90, 13)];
//    [_contentView addSubview:_commentLabel];
    
    _likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _likeButton.size = CGSizeMake(85, 13);
    [_likeButton setImage:[UIImage imageNamed:@"dynamic_like"] forState:UIControlStateNormal];
    [_likeButton setImage:[UIImage imageNamed:@"dynamic_liked"] forState:UIControlStateSelected];
    [_likeButton setTitle:@" Like" forState:UIControlStateNormal];
    [_likeButton setTitleColor:kGrayColor forState:UIControlStateNormal];
    _likeButton.titleLabel.font = SystemSmallFont;
    [_likeButton addTarget:self action:@selector(actionForLike:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_likeButton];
    
//    _likeLabel = [UILabel new];
//    _likeLabel.text = @"Like";
//    _likeLabel.textColor = kGrayColor;
//    _likeLabel.font = SystemSmallFont;
//    _likeLabel.textAlignment = NSTextAlignmentCenter;
//    [_likeLabel setFrame:CGRectMake(_likeButton.right, _commentButton.top, 40, 13)];
//    [_contentView addSubview:_likeLabel];
    
    return self;
}

-(void)setLayout:(KStatusLayout *)layout
{
    _layout = layout;
    self.height = layout.height;
    _contentView.top = 0;
    _contentView.height = layout.height;
    _contentView.origin = CGPointMake(0, 0);
    _contentView.width = kScreenWidth;
    _contentLabel.height = layout.textHeight;
    
    CGFloat top = 5;
    @weakify(_avatarView);
    if (layout.status.isAd) {
        _nameLabel.textLayout = layout.titleLayout;
        
    }else{
        [_avatarView setImageWithURL:[NSURL URLWithString:layout.status.profile ? [KGetImageURL stringByAppendingString:layout.status.profile] : @""] placeholder:[UIImage imageNamed:KImagePlaceholder] options:kNilOptions progress:nil transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
            if (!image) {
                weak__avatarView.image = [[UIImage imageNamed:KImagePlaceholder] imageByResizeToSize:CGSizeMake(KStatusCellAvatarWH, KStatusCellAvatarWH)];
            }else{
                weak__avatarView.image = [image imageByResizeToSize:weak__avatarView.size contentMode:UIViewContentModeScaleAspectFill];
            }
        }];
        
        _nameLabel.textLayout = layout.nameLayout;
        _timeLabel.textLayout = layout.timeLayout;
        _contentLabel.textLayout = layout.textLayout;
        top = _contentLabel.bottom + top;
        
        if (layout.imagesHeight > 0.0) {
            [self layoutPic:top];
        }else{
            [self _hideImageViews];
        }
        
        _likesLabel.top = CGRectGetMaxY(self.contentLabel.frame) + layout.imagesHeight + KStatusCellPadding;//top + layout.imagesHeight + KStatusCellPadding;
        _likesLabel.width = (kScreenWidth -  2 * self.contentLabel.left)/2;
        _likesLabel.height = 15;
        _likesLabel.left = _avatarView.left;
        _likesLabel.textLayout = layout.likeTextLayout;
        
        _commentsLabel.top = CGRectGetMaxY(self.contentLabel.frame) + layout.imagesHeight + KStatusCellPadding;
        _commentsLabel.height = 15;
        _commentsLabel.left = CGRectGetMaxX(_likesLabel.frame);
        _commentsLabel.width = kScreenWidth - _avatarView.left - CGRectGetMaxX(_likesLabel.frame);
        _commentsLabel.textLayout = layout.commentTextLayout;
        
        _seperateLine.top = CGRectGetMaxY(_commentsLabel.frame) + KStatusCellPadding;
        _seperateLine.left = 0;
        
        _commentButton.top = CGRectGetMaxY(_seperateLine.frame) + KStatusCellPadding * 1.5;
        _commentButton.left = _avatarView.left;
    
//        _commentLabel.top = _commentButton.top;
        
        _likeButton.centerY = _commentButton.centerY;
        _likeButton.left = CGRectGetMaxX(_commentButton.frame) + KStatusCellPadding;
        _likeButton.selected = layout.status.isLike;
        
//        _likeLabel.top = _likeButton.top;
//        _likeLabel.left = CGRectGetMaxX(_likeButton.frame);
    }
}

-(void)layoutPic:(CGFloat)imageTop
{
    CGSize picSize =  _layout.picSize;
    NSArray *pics = _layout.status.imageUrls;
    int picsCount = (int)pics.count;
    for (int i = 0; i < 9; i++) {
        UIImageView *imageView = _picViews[i];
        if (i >= picsCount) {
            [imageView cancelCurrentImageRequest];
            imageView.hidden = YES;
        } else {
            imageView.hidden = NO;
            CGPoint origin = {0};
            {
                origin.x = _avatarView.left + (i % 3) * (picSize.width + kCellPaddingPic);
                origin.y = imageTop + (int)(i / 3) * (picSize.height + kCellPaddingPic);
            }
            imageView.frame = (CGRect){.origin = origin, .size = picSize};
            
            NSString* url = pics[i];
            //[imageView setImageWithURL:[NSURL URLWithString:url?:@""] placeholder:[UIImage imageNamed:@"github"]];
            @weakify(imageView);
            [imageView setImageWithURL:[NSURL URLWithString:[KGetImageURL stringByAppendingString:url]?:@""] placeholder:[UIImage imageNamed:@"user_placeholder_icon"] options:kNilOptions completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                weak_imageView.image = [image imageByResizeToSize:picSize contentMode:UIViewContentModeScaleAspectFill];
            }];
            
        }
    }
}

- (void)_hideImageViews {
    for (UIImageView *imageView in _picViews) {
        imageView.hidden = YES;
    }
}

#pragma mark 点击事件

- (IBAction)actionForLike:(id)sender {
    UIButton *btn = sender;
    if (btn.selected) {
        return;
    }
    btn.selected = YES;
    NSMutableAttributedString *like = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%ld People likes this",self.layout.status.likeQty + 1]];
    like.font = SystemFont;
    like.color = kDarkGrayColor;
    like.backgroundColor = kClearColor;
    like.lineBreakMode = NSLineBreakByCharWrapping;
    YYTextContainer* container = [YYTextContainer new];
    container.size = CGSizeMake(KStatusCellContentWidth-KStatusCellAvatarWH - KStatusCellPadding*3, HUGE);
    container.maximumNumberOfRows = 1;
    YYTextLayout *likeTextLayout = [YYTextLayout layoutWithContainer:container text:like];
    self.likesLabel.textLayout = likeTextLayout;
    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didClickLike:)]) {
        [self.cell.delegate didClickLike:self.layout];
    }
}

- (IBAction)actionForComment:(id)sender {
//    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didClickComment:)]) {
//        [self.cell.delegate didClickComment:self.layout];
//    }
    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didClickCommentLabel:)]) {
        [self.cell.delegate didClickCommentLabel:self.layout];
    }
}

- (void)actionForUser {
    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didClickUser:)]) {
        [self.cell.delegate didClickUser:self.layout];
    }
}

- (void)actionForLongUser {
    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didLongClickUser:)]) {
        [self.cell.delegate didLongClickUser:self.layout];
    }
}

- (void)actionForCommentLabel {
    if (self.cell.delegate && [self.cell.delegate respondsToSelector:@selector(didClickCommentLabel:)]) {
        [self.cell.delegate didClickCommentLabel:self.layout];
    }
}

@end

@implementation KStatusTableViewCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _statusView = [KStatusView new];
        _statusView.cell = self;
        [self.contentView addSubview:_statusView];
    }
    return self;
}

-(void)setLayout:(KStatusLayout *)layout
{
    self.height = layout.height;
    self.contentView.height = layout.height;
    _statusView.layout = layout;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
